import { useState } from 'react';
import { Form, Input, Button, Card, Typography, Tabs, message, Modal, ConfigProvider, theme } from 'antd';
import { UserOutlined, MailOutlined, PhoneOutlined, IdcardOutlined, SafetyOutlined, LoginOutlined, UserAddOutlined, EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useMutation } from '@tanstack/react-query';
import { login, register } from '../services/api';
import { useMediaQuery } from 'react-responsive';
import { LoginData, RegisterData } from '../types/api';
import '../styles/Login.css';

const { Title, Text, Link } = Typography;

const Login = () => {
    const [activeTab, setActiveTab] = useState('login');
    const [loginForm] = Form.useForm();
    const [registerForm] = Form.useForm();
    const navigate = useNavigate();
    const isMobile = useMediaQuery({ maxWidth: 768 });

    // 法律条款弹窗相关状态
    const [modalVisible, setModalVisible] = useState(false);
    const [modalTitle, setModalTitle] = useState('');
    const [modalContent, setModalContent] = useState('');

    // 关闭弹窗
    const closeModal = () => {
        setModalVisible(false);
        setModalTitle('');
        setModalContent('');
    };

    // 暗黑主题配置
    const themeConfig = {
        algorithm: theme.darkAlgorithm,
        token: {
            colorPrimary: '#3B82F6',
            colorBgContainer: 'rgba(30, 30, 30, 0.95)',
            colorBgElevated: 'rgba(30, 30, 30, 0.95)',
            colorBorder: '#2a2a2a',
            colorText: '#ffffff',
            colorTextSecondary: 'rgba(255, 255, 255, 0.65)',
            fontFamily: "'Huninn', 'PingFang SC', sans-serif",
        },
    };

    // 登录请求
    const loginMutation = useMutation({
        mutationFn: login,
        onSuccess: (data: any) => {
            localStorage.setItem('token', data.access_token);
            localStorage.setItem('userId', data.userId);
            localStorage.setItem('username', data.username);
            message.success('登录成功');
            navigate('/dashboard');
        },
        onError: (error: any) => {
            console.error('Login error:', error);
            message.error('登录失败，请检查用户名和密码');
        },
    });

    // 注册请求
    const registerMutation = useMutation({
        mutationFn: register,
        onSuccess: () => {
            message.success('注册成功，请登录');
            setActiveTab('login');
            registerForm.resetFields();
        },
        onError: (error: any) => {
            console.error('Register error:', error);
            message.error('注册失败，请稍后再试');
        },
    });

    // 处理登录表单提交
    const handleLogin = (values: LoginData) => {
        loginMutation.mutate(values);
    };

    // 处理注册表单提交
    const handleRegister = (values: RegisterData & { confirmPassword: string }) => {
        const { confirmPassword, ...registerData } = values;
        registerMutation.mutate(registerData);
    };

    // 移动端布局
    if (isMobile) {
        return (
            <ConfigProvider theme={themeConfig}>
                <div className="login-container">
                    <div className="login-mobile-logo">
                        <img src="/自由编导-02.png" alt="Logo" />
                    </div>

                    <Card className="login-mobile-card">
                        <div className="login-title-section-mobile">
                            <div>
                                <Title level={3} className="login-title">
                                    {activeTab === 'login' ? '用户登录' : '用户注册'}
                                </Title>
                            </div>
                            <div>
                                <Text className="login-subtitle">{activeTab === 'login' ? '请输入您的账号信息' : '创建您的专属账号'}</Text>
                            </div>
                        </div>

                        <div key={activeTab}>
                            <Tabs
                                activeKey={activeTab}
                                onChange={setActiveTab}
                                centered
                                size="small"
                                items={[
                                    {
                                        key: 'login',
                                        label: (
                                            <span>
                                                <LoginOutlined style={{ marginRight: 8 }} />
                                                用户名密码登录
                                            </span>
                                        ),
                                        children: (
                                            <div className="login-form">
                                                <Form form={loginForm} onFinish={handleLogin} layout="vertical" size="small">
                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="phone"
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请输入账号',
                                                                },
                                                                {
                                                                    pattern: /^1[3-9]\d{9}$/,
                                                                    message: '请输入正确的手机号',
                                                                },
                                                            ]}
                                                        >
                                                            <Input prefix={<PhoneOutlined style={{ color: '#3B82F6' }} />} placeholder="账号（手机号）" />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="username"
                                                            rules={[
                                                                {
                                                                    max: 50,
                                                                    message: '用户名最多50个字符',
                                                                },
                                                            ]}
                                                        >
                                                            <Input prefix={<IdcardOutlined style={{ color: '#3B82F6' }} />} placeholder="用户名" />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="password"
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请输入密码',
                                                                },
                                                            ]}
                                                        >
                                                            <Input.Password
                                                                prefix={<SafetyOutlined style={{ color: '#3B82F6' }} />}
                                                                placeholder="密码"
                                                                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                                                            />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-button-container">
                                                        <Form.Item>
                                                            <Button type="primary" htmlType="submit" block loading={loginMutation.isPending} icon={<LoginOutlined />}>
                                                                登录
                                                            </Button>
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-link-container">
                                                        <Text className="login-link-text">
                                                            还没有账号？
                                                            <Link className="login-link" onClick={() => setActiveTab('register')}>
                                                                立即注册
                                                            </Link>
                                                        </Text>
                                                    </div>
                                                </Form>
                                            </div>
                                        ),
                                    },
                                    {
                                        key: 'register',
                                        label: (
                                            <span>
                                                <UserAddOutlined style={{ marginRight: 8 }} />
                                                注册
                                            </span>
                                        ),
                                        children: (
                                            <div className="login-form">
                                                <Form form={registerForm} onFinish={handleRegister} layout="vertical" size="small">
                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="username"
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请输入用户名',
                                                                },
                                                                {
                                                                    min: 3,
                                                                    max: 20,
                                                                    message: '用户名长度3-20个字符',
                                                                },
                                                                {
                                                                    pattern: /^[a-zA-Z0-9_]+$/,
                                                                    message: '只能包含字母、数字和下划线',
                                                                },
                                                            ]}
                                                        >
                                                            <Input prefix={<IdcardOutlined style={{ color: '#3B82F6' }} />} placeholder="用户名" />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="phone"
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请输入手机号',
                                                                },
                                                                {
                                                                    pattern: /^1[3-9]\d{9}$/,
                                                                    message: '请输入正确的手机号',
                                                                },
                                                            ]}
                                                        >
                                                            <Input prefix={<PhoneOutlined style={{ color: '#3B82F6' }} />} placeholder="手机号" />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="nickname"
                                                            rules={[
                                                                {
                                                                    max: 50,
                                                                    message: '昵称最多50个字符',
                                                                },
                                                            ]}
                                                        >
                                                            <Input prefix={<UserOutlined style={{ color: '#3B82F6' }} />} placeholder="昵称" />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="email"
                                                            rules={[
                                                                {
                                                                    type: 'email',
                                                                    message: '请输入有效的邮箱地址',
                                                                },
                                                                {
                                                                    max: 100,
                                                                    message: '邮箱地址最多100个字符',
                                                                },
                                                            ]}
                                                        >
                                                            <Input prefix={<MailOutlined style={{ color: '#3B82F6' }} />} placeholder="邮箱" />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="password"
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请输入密码',
                                                                },
                                                                {
                                                                    min: 6,
                                                                    message: '密码至少6个字符',
                                                                },
                                                            ]}
                                                        >
                                                            <Input.Password
                                                                prefix={<SafetyOutlined style={{ color: '#3B82F6' }} />}
                                                                placeholder="密码"
                                                                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                                                            />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="confirmPassword"
                                                            dependencies={['password']}
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请确认密码',
                                                                },
                                                                ({ getFieldValue }) => ({
                                                                    validator(_, value) {
                                                                        if (!value || getFieldValue('password') === value) {
                                                                            return Promise.resolve();
                                                                        }
                                                                        return Promise.reject(new Error('两次输入的密码不一致'));
                                                                    },
                                                                }),
                                                            ]}
                                                        >
                                                            <Input.Password
                                                                prefix={<SafetyOutlined style={{ color: '#3B82F6' }} />}
                                                                placeholder="确认密码"
                                                                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                                                            />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-button-container">
                                                        <Form.Item>
                                                            <Button type="primary" htmlType="submit" block loading={registerMutation.isPending} icon={<UserAddOutlined />}>
                                                                注册
                                                            </Button>
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-link-container">
                                                        <Text className="login-link-text">
                                                            已有账号？
                                                            <Link className="login-link" onClick={() => setActiveTab('login')}>
                                                                立即登录
                                                            </Link>
                                                        </Text>
                                                    </div>
                                                </Form>
                                            </div>
                                        ),
                                    },
                                ]}
                            />
                        </div>
                    </Card>
                </div>
            </ConfigProvider>
        );
    }

    // 桌面端布局
    return (
        <ConfigProvider theme={themeConfig}>
            <div className="login-desktop-container">
                {/* 左侧背景区域 */}
                <div className="login-desktop-left">
                    <div className="login-desktop-left-content">
                        <img src="/自由编导-02.png" width={800} height={300} alt="Logo" />
                    </div>
                </div>

                {/* 右侧表单区域 */}
                <div className="login-desktop-right">
                    <Card className="login-desktop-card">
                        <div className="login-title-section">
                            <div>
                                <Title level={2} className="login-title">
                                    {activeTab === 'login' ? '用户登录' : '用户注册'}
                                </Title>
                            </div>
                            <div>
                                <Text className="login-subtitle">{activeTab === 'login' ? '请输入您的账号信息' : '创建您的专属账号'}</Text>
                            </div>
                        </div>

                        <div key={activeTab}>
                            <Tabs
                                activeKey={activeTab}
                                onChange={setActiveTab}
                                centered
                                size="large"
                                items={[
                                    {
                                        key: 'login',
                                        label: (
                                            <span>
                                                <LoginOutlined style={{ marginRight: 8 }} />
                                                用户名密码登录
                                            </span>
                                        ),
                                        children: (
                                            <div className="login-form">
                                                <Form form={loginForm} onFinish={handleLogin} layout="vertical">
                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="phone"
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请输入账号',
                                                                },
                                                                {
                                                                    pattern: /^1[3-9]\d{9}$/,
                                                                    message: '请输入正确的手机号',
                                                                },
                                                            ]}
                                                        >
                                                            <Input prefix={<PhoneOutlined style={{ color: '#3B82F6' }} />} placeholder="账号（手机号）" />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="username"
                                                            rules={[
                                                                {
                                                                    max: 50,
                                                                    message: '用户名最多50个字符',
                                                                },
                                                            ]}
                                                        >
                                                            <Input prefix={<IdcardOutlined style={{ color: '#3B82F6' }} />} placeholder="用户名" />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="password"
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请输入密码',
                                                                },
                                                            ]}
                                                        >
                                                            <Input.Password
                                                                prefix={<SafetyOutlined style={{ color: '#3B82F6' }} />}
                                                                placeholder="密码"
                                                                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                                                            />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-button-container">
                                                        <Form.Item>
                                                            <Button type="primary" htmlType="submit" block loading={loginMutation.isPending} icon={<LoginOutlined />}>
                                                                登录
                                                            </Button>
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-link-container">
                                                        <Text className="login-link-text">
                                                            还没有账号？
                                                            <Link className="login-link" onClick={() => setActiveTab('register')}>
                                                                立即注册
                                                            </Link>
                                                        </Text>
                                                    </div>
                                                </Form>
                                            </div>
                                        ),
                                    },
                                    {
                                        key: 'register',
                                        label: (
                                            <span>
                                                <UserAddOutlined style={{ marginRight: 8 }} />
                                                注册
                                            </span>
                                        ),
                                        children: (
                                            <div className="login-form">
                                                <Form form={registerForm} onFinish={handleRegister} layout="vertical">
                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="username"
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请输入用户名',
                                                                },
                                                                {
                                                                    min: 3,
                                                                    max: 20,
                                                                    message: '用户名长度3-20个字符',
                                                                },
                                                                {
                                                                    pattern: /^[a-zA-Z0-9_]+$/,
                                                                    message: '只能包含字母、数字和下划线',
                                                                },
                                                            ]}
                                                        >
                                                            <Input prefix={<IdcardOutlined style={{ color: '#3B82F6' }} />} placeholder="用户名" />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="phone"
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请输入手机号',
                                                                },
                                                                {
                                                                    pattern: /^1[3-9]\d{9}$/,
                                                                    message: '请输入正确的手机号',
                                                                },
                                                            ]}
                                                        >
                                                            <Input prefix={<PhoneOutlined style={{ color: '#3B82F6' }} />} placeholder="手机号" />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="nickname"
                                                            rules={[
                                                                {
                                                                    max: 50,
                                                                    message: '昵称最多50个字符',
                                                                },
                                                            ]}
                                                        >
                                                            <Input prefix={<UserOutlined style={{ color: '#3B82F6' }} />} placeholder="昵称" />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="email"
                                                            rules={[
                                                                {
                                                                    type: 'email',
                                                                    message: '请输入有效的邮箱地址',
                                                                },
                                                                {
                                                                    max: 100,
                                                                    message: '邮箱地址最多100个字符',
                                                                },
                                                            ]}
                                                        >
                                                            <Input prefix={<MailOutlined style={{ color: '#3B82F6' }} />} placeholder="邮箱" />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="password"
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请输入密码',
                                                                },
                                                                {
                                                                    min: 6,
                                                                    message: '密码至少6个字符',
                                                                },
                                                            ]}
                                                        >
                                                            <Input.Password
                                                                prefix={<SafetyOutlined style={{ color: '#3B82F6' }} />}
                                                                placeholder="密码"
                                                                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                                                            />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-form-container">
                                                        <Form.Item
                                                            name="confirmPassword"
                                                            dependencies={['password']}
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请确认密码',
                                                                },
                                                                ({ getFieldValue }) => ({
                                                                    validator(_, value) {
                                                                        if (!value || getFieldValue('password') === value) {
                                                                            return Promise.resolve();
                                                                        }
                                                                        return Promise.reject(new Error('两次输入的密码不一致'));
                                                                    },
                                                                }),
                                                            ]}
                                                        >
                                                            <Input.Password
                                                                prefix={<SafetyOutlined style={{ color: '#3B82F6' }} />}
                                                                placeholder="确认密码"
                                                                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                                                            />
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-button-container">
                                                        <Form.Item>
                                                            <Button type="primary" htmlType="submit" block loading={registerMutation.isPending} icon={<UserAddOutlined />}>
                                                                注册
                                                            </Button>
                                                        </Form.Item>
                                                    </div>

                                                    <div className="login-link-container">
                                                        <Text className="login-link-text">
                                                            已有账号？
                                                            <Link className="login-link" onClick={() => setActiveTab('login')}>
                                                                立即登录
                                                            </Link>
                                                        </Text>
                                                    </div>
                                                </Form>
                                            </div>
                                        ),
                                    },
                                ]}
                            />
                        </div>
                    </Card>
                </div>

                {/* 气泡装饰效果 */}
                {[...Array(8)].map((_, i) => (
                    <div
                        key={i}
                        className="login-bubble"
                        style={{
                            left: `${48 + (i % 3) * 2}%`,
                            top: `${15 + i * 10}%`,
                            width: `${60 - i * 5}px`,
                            height: `${60 - i * 5}px`,
                            background: i % 2 === 0 ? 'rgba(255, 255, 255, 0.15)' : 'rgba(102, 126, 234, 0.2)',
                            animation: `float ${6 - i * 0.5}s ease-in-out infinite ${i * 0.5}s`,
                        }}
                    />
                ))}

                {/* 法律条款弹窗 */}
                <Modal title={modalTitle} open={modalVisible} onCancel={closeModal} footer={null} width={800} className="legal-modal">
                    <div className="legal-modal-content">
                        <div className="legal-modal-text">{modalContent}</div>
                    </div>
                </Modal>
            </div>
        </ConfigProvider>
    );
};

export default Login;
